package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.dto.ReservationDto;
import com.zzyl.entity.Reservation;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.ReservationMapper;
import com.zzyl.service.ReservationService;
import com.zzyl.utils.UserThreadLocal;
import com.zzyl.vo.ReservationVo;
import com.zzyl.vo.TimeCountVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Transactional
@Service
public class ReservationServiceImpl implements ReservationService {
//RESERVATION_CANCEL_COUNT_UPPER_LIMIT(1526, "今天取消次数已达上限，不可进行预约"),
    @Autowired
    private ReservationMapper reservationMapper;

    // 1.0 查询当天取消预约的数量
    @Override
    public Integer getCancelledReservationCount(Long updateBy) {
        LocalDateTime startTime =LocalDateTime.now().withHour(0).withMinute(0).withSecond(0);
        LocalDateTime endTime =LocalDateTime.now().withHour(23).withMinute(59).withSecond(59);

        return  reservationMapper.getCancelledReservationCountByUserId(
                startTime,
                endTime,
                updateBy);
    }


    // 2.2 查询每个时间段剩余预约次数
    @Override
    public List<TimeCountVo> getCountByEachTime(Long time) {
        LocalDateTime startTime = LocalDateTimeUtil.of(time);
        LocalDateTime endTime = startTime.plusHours(24);

        List<TimeCountVo> timeCountVos = new ArrayList<>();
        while (!startTime.isAfter(endTime)){
            Integer count = reservationMapper.getCountByEachTime(startTime, startTime.plusMinutes(30));
            if (count == null) {
                count = 0; // Initialize count to 0 if null
            }
            TimeCountVo timeCountVo = new TimeCountVo();
            timeCountVo.setTime(startTime);
            timeCountVo.setCount(6 - count);
            timeCountVos.add(timeCountVo);
            startTime = startTime.plusMinutes(30); // Move to the next time slot
        }
        return timeCountVos;
    }

    // 2.3 新增预约
    @Override
    public void addReservation(ReservationDto reservationDto) {
        // 当天取消次数大于等于 3次 就不能再预约
        Long userId = UserThreadLocal.getUserId();
        if (getCancelledReservationCount(userId) >= 3) {
            throw new BaseException(BasicEnum.RESERVATION_CANCEL_COUNT_UPPER_LIMIT);
        }
        //TODO：还有同一个手机号同一个时间段只能预约一次：phone  +  time
        String mobile = reservationDto.getMobile();
        LocalDateTime time = reservationDto.getTime();
        if (reservationMapper.countByMobile(mobile,time) > 0) {
            throw new BaseException(BasicEnum.TIME_ALREADY_RESERVATED_BY_PHONE);
        }

        // 允许添加预约

        Reservation reservation = BeanUtil.copyProperties(reservationDto, Reservation.class);
        reservation.setCreateBy(userId);// 添加创建人
        //reservation.setUpdateBy(UserThreadLocal.getUserId()); // 添加跟新人
        reservation.setStatus(0); // 给新增的预约，添加待报道状态 ，只是预约，还没去养老院报道状态
        reservationMapper.addReservation(reservation); //TODO： 代码有问题
    }



    // 2.4 分页查询预约
    @Override
    public PageResponse<ReservationVo> findByPage(Integer pageNum, Integer pageSize, Integer status, Long useId) {
        PageHelper.startPage(pageNum, pageSize);
        Page<Reservation> page = reservationMapper.findByPage(pageNum,pageSize,status, useId);
        return PageResponse.of(page, ReservationVo.class);
    }



    // 2.5 查询所有预约
    @Override
    public List<ReservationVo> findAll(String mobile, LocalDateTime of) {
        return List.of();
    }

    // 2.6 取消预约
    @Override
    public void cancelReservation(Long id) {
        //1 判断预约信息是否存在
      Reservation reservation=  reservationMapper.getReservationBy(id);
      if(reservation == null){
          throw new BaseException(BasicEnum.RESERVATION_NOT_EXIST);
      }
      //2 预约已经完成不能取消
      if(reservation.getStatus() == 1){
          throw new BaseException(BasicEnum.RESERVATION_CANNOT_CANCEL);
      }
      // 3 判断预约事件，是否过期
        LocalDateTime time = reservation.getTime();
        LocalDateTime now = LocalDateTime.now();

        int result = time.compareTo(now);

        if (result > 0) {
            // time 在 now 之后,可以取消预约
            System.out.println("预约时间在未来");
            Integer status = 2;
            reservationMapper.updateReservationByHand(id,status);
        }  else {
            // time 在 now 之前，提示系统已经自动取消预约
            System.out.println("预约时间已经过期");
            Integer status = 3;
            reservationMapper.updateReservationByHand(id,status);
            throw new BaseException(BasicEnum.RESERVATION__CANCELED_BY_SYSTEM);
        }

    }

    //2.7 系统自动更新预约 预约状态过期系统自动修改
    @Override
    public Integer updateReservationStatus(LocalDateTime now) {
        return  reservationMapper.updateReservation(now);

    }












}
